package cn.liangjintang.iptool;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    TextView textView;
    EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.tv);
        textView.setText(testLocalIpAddress());

        editText = (EditText) findViewById(R.id.editText);
    }

    public final String testLocalIpAddress() {
        String txt = "";
        try {
            // 遍历网络接口
            Enumeration<NetworkInterface> infos = NetworkInterface.getNetworkInterfaces();

            while (infos.hasMoreElements()) {
                // 获取网络接口
                NetworkInterface niFace = infos.nextElement();
                Enumeration<InetAddress> enumIpAddr = niFace.getInetAddresses();
                while (enumIpAddr.hasMoreElements()) {
                    InetAddress mInetAddress = enumIpAddr.nextElement();
                    txt += mInetAddress.getHostAddress() + "\n    " + test(mInetAddress) + "\n";
                }
            }

        } catch (SocketException e) {
        }
        return txt;
    }

    private String test(InetAddress address) {
        Method methods[] = InetAddress.class.getMethods();
        // 以is开头并且没有参数的方法
        for (Method method : methods) {
            if (method.getName().matches("is.*") && method.getParameterTypes().length == 0) {
                try {
                    if (Boolean.parseBoolean(method.invoke(address).toString()))
                        return method.getName() + "\n";
                } catch (Exception e) {

                }
            }
        }
        return "普通IP类型(一般为公网IP)";
    }

    @Override
    public void onClick(View v) {
        String txt="";
        InetAddress address = null;
        try {
            address = InetAddress.getByName(editText.getText().toString());
            txt= address.getHostAddress() + "\n    " + test(address) + "\n";
        } catch (UnknownHostException e) {
            txt="输入错误\n\n";
            e.printStackTrace();
        }
        textView.setText(txt+textView.getText());
    }
}
